package org.ling.xuan.entity.mo;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import lombok.Data;
import org.ling.xuan.entity.SvnInfo;
import org.ling.xuan.util.CmdUtil;
import org.ling.xuan.util.LoggerUtil;
import org.ling.xuan.util.LxStrUtil;

import java.io.File;
import java.util.Date;

@Data
public class ProjectSetting {
    private String id;
    /**
     * 本地路径前缀 文件提交,发送,打包需要替换的
     */
    private String localPre = "";
    /**
     * svnUrl前缀 http://231321321/321321/321321
     */
    private String svnPre = "";
    /**
     * 添加前缀 添加时匹配localPre替换
     */
    private String addPre = "";
    /**
     * 压缩目录前缀 压缩时相对添加文件的路径的根目录,也就是从哪一级开始压缩 例如:添加文件 /Sources/app/ifmpub/.../a.java  则 zipPre 配置为/Sources/app
     */
    private String zipPre = "";
    /**
     * 编译路径
     */
    private String compilePath = "";
    /**
     * 测试编译路径
     */
    private String testCompilePath = "";
    
    /**
     * 构建路径
     */
    private String buildPath = "";

    /**
     * 项目路径
     */
    private String projectPath = "";
    /**
     * 静态资源目录
     */
    private String webPath = "";
    /**
     * 项目名称projectName
     */
    private String projectName = "";
    
    /**
     * 统一提交路径 默认当前目录的父层级 为空则各子项目自行提交
     */
    private String unionCommitPath;
    /**
     * 创建时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date ctdTime;
    
    private String systemName = "";


    public static ProjectSetting initProjectSettingByProject(Project project) {
        ProjectSetting projectSetting = new ProjectSetting();
        String basePath = LxStrUtil.unionPath(project.getBasePath());
        projectSetting.setProjectPath(basePath);
        projectSetting.setProjectName(FileUtil.getName(basePath));
        String svnRoot = basePath + "/.svn";
        boolean f = FileUtil.exist(svnRoot);
        if (f) {
            try {
                SvnInfo svnInfo = new SvnInfo(CmdUtil.executeCommand(basePath, "svn info"));
                projectSetting.setSvnPre(svnInfo.getRemoteUrl());
                projectSetting.setAddPre(svnInfo.getRemoteRelativePath().substring(2));
                projectSetting.setZipPre(svnInfo.getRemoteRelativePath().substring(2));
            } catch (Exception e) {
                LoggerUtil.log(project, "获取项目svn信息失败:{}", e);
            }
        }
        String ideaRoot = basePath + "/.idea";
        if (FileUtil.exist(ideaRoot + "/artifacts")) {

            java.util.List<File> files = FileUtil.loopFiles(ideaRoot + "/artifacts", a -> a.getName().endsWith(".xml"));
            if (!files.isEmpty()) {
                String s = FileUtil.readUtf8String(files.get(0));
                JSONObject jsonObject = JSONUtil.xmlToJson(s);
                projectSetting.setBuildPath(jsonObject.getByPath("component.artifact.output-path", String.class).replace("$PROJECT_DIR$", basePath));
            }
        }
        ModuleManager moduleManager = ModuleManager.getInstance(project);
        if (moduleManager.getModules().length > 0) {
            Module module = moduleManager.getModules()[0];
            String cp = getModuleCompilerPath(basePath, module);
            if (StrUtil.isBlank(cp)) {
                cp = getProjectCompilerPath(basePath);
                if (StrUtil.isBlank(cp)) {
                    cp = basePath + "/target/classes";
                } else {
                    cp = cp + "/prodution/" + module.getName();
                }
            }
            projectSetting.setCompilePath(cp);
            String webRoot = getWebRoot(basePath, module);
            if (StrUtil.isBlank(webRoot)) {
                projectSetting.setWebPath(basePath + "/WebContent");
            } else {
                projectSetting.setWebPath(webRoot);
            }
        } else {
            projectSetting.setCompilePath(basePath);
            projectSetting.setWebPath(basePath + "/WebContent");
        }
        projectSetting.setUnionCommitPath(basePath.substring(0, basePath.lastIndexOf("/")));
        projectSetting.setLocalPre(basePath);
        projectSetting.setSystemName("综合理财3.0");
        return projectSetting;
    }

    private static String getWebRoot(String basePath, Module module) {
        String url = "";
        try {
            String ss = module.getModuleFilePath();
            String s = FileUtil.readUtf8String(ss);
            JSONObject jsonObject = JSONUtil.xmlToJson(s);
            JSONObject jo = jsonObject.getJSONObject("module");
            JSONArray cs = new JSONArray();
            try {
                JSONObject ll = jo.getJSONObject("component");
                cs.add(ll);
            } catch (ClassCastException e) {
                cs = jo.getJSONArray("component");
            }
            for (int i = 0; i < cs.size(); i++) {
                if (cs.getJSONObject(i).getStr("name").equals("FacetManager")) {
                    JSONObject jf = cs.getJSONObject(i);
                    JSONArray facts = new JSONArray();
                    try {
                        JSONObject ll = jf.getJSONObject("facet");
                        facts.add(ll);
                    } catch (ClassCastException e) {
                        facts = jo.getJSONArray("facet");
                    }
                    if (facts.size() > 0) {
                        String u = facts.getJSONObject(0).getJSONObject("configuration").getJSONObject("webroots").getJSONObject("root").getStr("url");
                        if (StrUtil.isNotBlank(u)) {
                            url = LxStrUtil.unionPath(u)
                                    .replace("$MODULE_DIR$", basePath)
                                    .replace("file://", "")
                                    .replace("File://", "");
                        }
                    }
                }
            }
        } catch (Exception e) {

        }
        return url;
    }

    public static String getProjectCompilerPath(String basePath) {
        String url = "";
        try {
            String ss = basePath + "/.idea/misc.xml";
            String s = FileUtil.readUtf8String(ss);
            JSONObject jsonObject = JSONUtil.xmlToJson(s);
            JSONObject jo = jsonObject.getJSONObject("project");
            JSONArray cs = new JSONArray();
            try {
                JSONObject ll = jo.getJSONObject("component");
                cs.add(ll);
            } catch (ClassCastException e) {
                cs = jo.getJSONArray("component");
            }
            for (int i = 0; i < cs.size(); i++) {
                if (cs.getJSONObject(i).getStr("name").equals("ProjectRootManager")) {
                    String u = cs.getJSONObject(i).getJSONObject("output").getStr("url");
                    if (StrUtil.isNotBlank(u)) {
                        url = LxStrUtil.unionPath(u).replace("$PROJECT_DIR$", basePath)
                                .replace("file://", "")
                                .replace("File://", "");
                    }
                }
            }
        } catch (Exception e) {

        }
        return url;
    }


    public static String getModuleCompilerPath(String basePath, Module module) {
        String url = "";
        try {
            String ss = module.getModuleFilePath();
            String s = FileUtil.readUtf8String(ss);
            JSONObject jsonObject = JSONUtil.xmlToJson(s);
            JSONObject jo = jsonObject.getJSONObject("module");
            JSONArray cs = new JSONArray();
            try {
                JSONObject ll = jo.getJSONObject("component");
                cs.add(ll);
            } catch (ClassCastException e) {
                cs = jo.getJSONArray("component");
            }
            for (int i = 0; i < cs.size(); i++) {
                if (cs.getJSONObject(i).getStr("name").equals("NewModuleRootManager")) {
                    String u = cs.getJSONObject(i).getJSONObject("output").getStr("url");
                    if (StrUtil.isNotBlank(u)) {
                        url = LxStrUtil.unionPath(u).replace("$MODULE_DIR$", basePath)
                                .replace("file://", "")
                                .replace("File://", "");
                    }
                }
            }
        } catch (Exception e) {

        }
        return url;
    }
}
